package com.example.hics_s.controller;

import com.example.hics_s.mapper.hicsMapper;
import com.example.hics_s.util.APIResultUtil;
import com.example.hics_s.util.MybatisUtil;
import com.example.hics_s.entity.hics_s;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api")
public class API {

    // 定义一个密钥常量，用于验证请求的合法性
    private static final String SECRET_PASSCODE = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    /**
     * 添加用户数据
     *
     * @param passCode    请求密钥
     * @param machineID   机器ID
     * @param cpu         CPU信息
     * @param gpu         GPU信息
     * @param memory      内存信息
     * @param storage     存储信息
     * @param motherboard 主板信息
     * @param macAddress  MAC地址
     * @return API结果
     */
    @RequestMapping("addUser")
    public Object addDate(@RequestParam(value = "passCode") String passCode,
                          @RequestParam(value = "machineID") String machineID,
                          @RequestParam(value = "cpu") String cpu,
                          @RequestParam(value = "gpu") String gpu,
                          @RequestParam(value = "memory") String memory,
                          @RequestParam(value = "storage") String storage,
                          @RequestParam(value = "motherboard") String motherboard,
                          @RequestParam(value = "macAddress") String macAddress) {
        // 验证密钥
        if (!SECRET_PASSCODE.equals(passCode)) {
            System.out.println("Illegal access");
            return APIResultUtil.apiResult(false, "密钥错误, 数据不可接受", null);
        }
        try {
            //        获取SqlSession
            SqlSession sqlSession = MybatisUtil.sqlSession();
            hicsMapper mapper = sqlSession.getMapper(hicsMapper.class);
//        判断MACGINEID是否存在
            List<hics_s> hics_s = mapper.listSomeDate(machineID);
            int i;
            if (!hics_s.isEmpty()) {
//           如果有值就修改数据
                i = mapper.updateDate(machineID, cpu, gpu, memory, storage, motherboard, macAddress);
            } else {
//            如果没有值就创建数据
                i = mapper.addDate(machineID, cpu, gpu, memory, storage, motherboard, macAddress);
            }
//            提交事务
            sqlSession.commit();
//            关闭连接
            sqlSession.close();
            // 根据操作结果返回相应的 API 响应
            if (i == 1) {
                return APIResultUtil.apiResult(true, "数据已上传", null);

            } else {
                System.out.println("UpdateFail");
                return APIResultUtil.apiResult(false, "更新失败", null);
            }
        } catch (Exception e) {
//            出问题了，直接返回错误
            System.out.println("SystemFail,ErrorMessage:" + e.getMessage());
            return APIResultUtil.apiResult(false, "服务器出现错误", null);

        }
    }
}